import express from 'express';
import glob from 'glob';
import path from 'path';
const app = express();

// 自动遍历项目数  遍历成接口方法
glob(
    path.join(__dirname, '/controllers/**/*.js'),
    {},
    (err: Error, files: string[]) => {
        if (err) return console.error('遍历树出错' + err);
        files.forEach((file: string) => {
            const instance: any = require(file);
            const roots: string = path
                .join(__dirname, '/controllers')
                .replace(/\\/g, '/');
            const urlPath: string = file.replace(roots, '').replace(/\.[^.]*$/g, '');
            const methods: string[] = Object.keys(instance);
            methods.forEach((method: string) => {
                app[method.toLowerCase()](urlPath, instance[method]);
            });
        });
    }
);

app.all('*', function (req, res, next) {
    // 设置允许跨域的域名，*代表允许任意域名跨域
    res.header('Access-Control-Allow-Origin', '*');
    // 允许的header类型
    res.header('Access-Control-Allow-Headers', 'content-type');
    // 跨域允许的请求方式
    res.header('Access-Control-Allow-Methods', 'POST,GET');
    if (req.method.toLowerCase() === 'options') res.send(200);
    // 让options尝试请求快速结束
    else next();
});

const server: any = app.listen(3002, () => {
    console.log('监听成功', 'http://localhost:' + server.address().port);
});
